import React, { useState } from 'react';
import { Card, Descriptions, Button, Form, Input, Select, Radio, Space, Modal, Tabs } from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import './styles.css';

interface RuleDetailData {
  id: string;
  ruleCode: string;
  ruleName: string;
  ruleType: string;
  sourceFormat: string;
  targetFormat: string;
  status: string;
  description: string;
  createTime: string;
  updateTime: string;
  conversionLogic: string;
}

// 模拟数据
const mockDetail: RuleDetailData = {
  id: 'RULE001',
  ruleCode: 'AMOUNT_CONVERT',
  ruleName: '金额单位转换',
  ruleType: '数值转换',
  sourceFormat: '元',
  targetFormat: '万元',
  status: 'enabled',
  description: '将金额从元转换为万元',
  createTime: '2023-12-15 14:30:00',
  updateTime: '2023-12-15 14:30:00',
  conversionLogic: `
// 金额单位转换逻辑
function convert(value) {
  // 输入验证
  if (typeof value !== 'number') {
    throw new Error('输入值必须是数字类型');
  }
  
  // 转换逻辑：元转换为万元
  const result = value / 10000;
  
  // 保留2位小数
  return Number(result.toFixed(2));
}
`
};

const ruleTypeOptions = [
  { value: 'number', label: '数值转换' },
  { value: 'date', label: '日期转换' },
  { value: 'enum', label: '枚举转换' },
  { value: 'string', label: '字符串转换' },
  { value: 'custom', label: '自定义转换' }
];

const SemanticRuleDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [detail, setDetail] = useState(mockDetail);
  const [isEditing, setIsEditing] = useState(false);
  const [activeTab, setActiveTab] = useState('basic');

  const handleBack = () => {
    navigate(-1);
  };

  const handleEdit = () => {
    setIsEditing(true);
    form.setFieldsValue(detail);
  };

  const handleSave = () => {
    form.validateFields().then(values => {
      console.log('保存规则:', values);
      setIsEditing(false);
      // 更新详情数据
      setDetail({ ...detail, ...values });
    });
  };

  const handleCancel = () => {
    setIsEditing(false);
    form.resetFields();
  };

  const handleTest = () => {
    Modal.info({
      title: '测试转换规则',
      content: '规则测试功能待实现'
    });
  };

  const tabItems = [
    {
      key: 'basic',
      label: '基本信息',
      children: (
        <Form
          form={form}
          layout="vertical"
          disabled={!isEditing}
          initialValues={detail}
          className="rule-form"
        >
          <Form.Item
            name="ruleCode"
            label="规则编码"
            rules={[{ required: true, message: '请输入规则编码' }]}
          >
            <Input placeholder="请输入规则编码" />
          </Form.Item>
          <Form.Item
            name="ruleName"
            label="规则名称"
            rules={[{ required: true, message: '请输入规则名称' }]}
          >
            <Input placeholder="请输入规则名称" />
          </Form.Item>
          <Form.Item
            name="ruleType"
            label="规则类型"
            rules={[{ required: true, message: '请选择规则类型' }]}
          >
            <Select options={ruleTypeOptions} placeholder="请选择规则类型" />
          </Form.Item>
          <Form.Item
            name="sourceFormat"
            label="源格式"
            rules={[{ required: true, message: '请输入源格式' }]}
          >
            <Input placeholder="请输入源格式" />
          </Form.Item>
          <Form.Item
            name="targetFormat"
            label="目标格式"
            rules={[{ required: true, message: '请输入目标格式' }]}
          >
            <Input placeholder="请输入目标格式" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Radio.Group>
              <Radio value="enabled">启用</Radio>
              <Radio value="disabled">停用</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={4} placeholder="请输入描述" />
          </Form.Item>
        </Form>
      )
    },
    {
      key: 'logic',
      label: '转换逻辑',
      children: (
        <div className="logic-editor">
          <Form.Item
            name="conversionLogic"
            label="转换函数"
            rules={[{ required: true, message: '请输入转换逻辑' }]}
          >
            <Input.TextArea
              rows={15}
              placeholder="请输入JavaScript转换函数"
              value={detail.conversionLogic}
              onChange={e => setDetail({ ...detail, conversionLogic: e.target.value })}
              disabled={!isEditing}
            />
          </Form.Item>
          <div className="logic-actions">
            <Button onClick={handleTest}>测试</Button>
          </div>
        </div>
      )
    }
  ];

  return (
    <div className="semantic-rule-detail-container">
      <Card
        title={
          <Space>
            <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
              返回
            </Button>
            <span>{id ? '编辑规则' : '新增规则'}</span>
          </Space>
        }
        extra={
          <Space>
            {!isEditing ? (
              <Button type="primary" icon={<SaveOutlined />} onClick={handleEdit}>
                编辑
              </Button>
            ) : (
              <>
                <Button onClick={handleCancel}>取消</Button>
                <Button type="primary" icon={<SaveOutlined />} onClick={handleSave}>
                  保存
                </Button>
              </>
            )}
          </Space>
        }
        className="detail-card"
      >
        {id && !isEditing && (
          <Descriptions title="基本信息" bordered className="info-descriptions">
            <Descriptions.Item label="规则编码">{detail.ruleCode}</Descriptions.Item>
            <Descriptions.Item label="规则名��">{detail.ruleName}</Descriptions.Item>
            <Descriptions.Item label="规则类型">{detail.ruleType}</Descriptions.Item>
            <Descriptions.Item label="源格式">{detail.sourceFormat}</Descriptions.Item>
            <Descriptions.Item label="目标格式">{detail.targetFormat}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Radio.Group value={detail.status} disabled>
                <Radio value="enabled">启用</Radio>
                <Radio value="disabled">停用</Radio>
              </Radio.Group>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{detail.createTime}</Descriptions.Item>
            <Descriptions.Item label="更新时间">{detail.updateTime}</Descriptions.Item>
            <Descriptions.Item label="描述" span={3}>
              {detail.description}
            </Descriptions.Item>
          </Descriptions>
        )}

        {(isEditing || !id) && (
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            items={tabItems}
            className="detail-tabs"
          />
        )}
      </Card>
    </div>
  );
};

export default SemanticRuleDetail; 